package me.wz.util.sdbc;

import java.sql.CallableStatement;
import java.sql.SQLException;

/**
 * @param <T>
 * @see org.apache.commons.dbutils.OutParameter
 */
public class OutParameter<T> {
    private final int sqlType;
    private final Class<T> javaType;
    private T value = null;

    public OutParameter(int sqlType, Class<T> javaType) {
        this.sqlType = sqlType;
        this.javaType = javaType;
    }

    public OutParameter(int sqlType, Class<T> javaType, T value) {
        this.sqlType = sqlType;
        this.javaType = javaType;
        this.value = value;
    }

    public int getSqlType() {
        return this.sqlType;
    }

    public Class<T> getJavaType() {
        return this.javaType;
    }

    public T getValue() {
        return this.value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    public void setValue(CallableStatement stmt, int index) throws SQLException {
        Object object = stmt.getObject(index);
        this.value = this.javaType.cast(object);
    }

    public void register(CallableStatement stmt, int index) throws SQLException {
        stmt.registerOutParameter(index, this.sqlType);
        if (this.value != null) {
            stmt.setObject(index, this.value);
        }

    }

    public String toString() {
        return "OutParameter{sqlType=" + this.sqlType + ", javaType=" + this.javaType + ", value=" + this.value + '}';
    }
}
